package com.lanyam.travel.base.service.impl;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.lanyam.travel.base.entity.vo.DistrUserVo;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.bouncycastle.crypto.tls.HashAlgorithm;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.OrderComparator.OrderSourceProvider;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lanyam.travel.base.controller.OrderController;
import com.lanyam.travel.base.dao.PermissionMapper;
import com.lanyam.travel.base.dao.RoleMapper;
import com.lanyam.travel.base.dao.RoleMenuMapper;
import com.lanyam.travel.base.dao.RolePermissionMapper;
import com.lanyam.travel.base.dao.TravelMenuMapper;
import com.lanyam.travel.base.dao.TravelOrderMapper;
import com.lanyam.travel.base.dao.UserMapper;
import com.lanyam.travel.base.entity.DistrUser;
import com.lanyam.travel.base.entity.Permission;
import com.lanyam.travel.base.entity.Role;
import com.lanyam.travel.base.entity.RolePermission;
import com.lanyam.travel.base.entity.ScenicHotel;
import com.lanyam.travel.base.entity.TravelMenu;
import com.lanyam.travel.base.entity.User;
import com.lanyam.travel.base.entity.vo.FormReport;
import com.lanyam.travel.base.entity.vo.TravelOrderVo;
import com.lanyam.travel.base.entity.vo.UserVo;
import com.lanyam.travel.base.service.IDistrUserService;
import com.lanyam.travel.base.service.UserService;
import com.lanyam.travel.base.utils.MD5Utils;

@Service
public class UserServiceImpl implements UserService {

	@Autowired
	private UserMapper userMapper;
	
	@Autowired
	private RoleMapper roleMapper;
	
	@Autowired
	private PermissionMapper permissionMapper;
	
	@Autowired
	private RolePermissionMapper rolePermissionMapper;
	
	@Autowired
	private IDistrUserService distrUserService;
	
	@Autowired
	private RoleMenuMapper roleMenuMapper;
	
	@Autowired
	private TravelOrderMapper travelOrderMapper;
	
	Logger logger = Logger.getLogger(UserServiceImpl.class);
	
	@Override
	public User queryPhoneIsExist(String phone) {
		// TODO Auto-generated method stub
		Map<String,Object> paraMap = new HashMap<String, Object>();
		paraMap.put("phone", phone);
		List<User> users = userMapper.selectByMap(paraMap);
		if(null != users && users.size() > 0)
		{
			return users.get(0);
		}
		return null;
	}

	@Override
	public void saveUser(User user) {
		// TODO Auto-generated method stub
		userMapper.insert(user);
	}

	@Override
	public User queryUserForLogin(String phone, String md5Str) {
		// TODO Auto-generated method stub
		Map<String,Object> paraMap = new HashMap<String, Object>();
		paraMap.put("phone", phone);
		paraMap.put("password", md5Str);
		List<User> users = userMapper.selectByMap(paraMap);
		if(null != users && users.size() > 0)
		{
			return users.get(0);
		}
		return null;
	}

	@Override
	public Role getRoleByUserId(String userId) {
		// TODO Auto-generated method stub
		Role role = userMapper.selectRoleInUser(userId);
		return role;
	}

	@Override
	public User getUserByOpenid(String openid) {
		// TODO Auto-generated method stub
		QueryWrapper<User> wrapper = new QueryWrapper<User>();
		wrapper.eq("openid", openid);
		User user = userMapper.selectOne(wrapper);
		return user;
	}

	@Override
	public Page<UserVo> queryAdminPage(int pageNum, int pageSize, Map<String, String> reqPara) {
		// TODO Auto-generated method stub
		Map<String,Object> paraMap = new HashMap<String, Object>();
		//supplyId不为空，则是供应商查询自己的订单，为空的话是管理员查询所有订单
		if(null != reqPara)
		{
			String supplierId = reqPara.get("supplierId");
			if(!StringUtils.isEmpty(supplierId))
			{
				//供应商
				paraMap.put("supplierId", supplierId);
			}
			String id = reqPara.get("id");
			if(!StringUtils.isEmpty(id))
			{
				paraMap.put("id", id);
			}
			String roleId = reqPara.get("roleId");
			if(!StringUtils.isEmpty(roleId))
			{
				paraMap.put("roleId", roleId);
			}
			String name = reqPara.get("name");
			if(!StringUtils.isEmpty(name))
			{
				paraMap.put("name", name);
			}
			String phone = reqPara.get("phone");
			if(!StringUtils.isEmpty(phone))
			{
				paraMap.put("phone", phone);
			}
			String createDate = reqPara.get("createDate");
			if(!StringUtils.isEmpty(createDate))
			{
				System.out.println(createDate);
				Date date = new Date(createDate);
				paraMap.put("createDate", date);
			}
		}
		
		Page<UserVo> page = new Page<UserVo>(pageNum,pageSize);
		Page<UserVo> ipage = userMapper.queryAdminPage(page, paraMap);
		return ipage;
		
	}
	
	@Override
	public List<User> queryUsersByPage(int pageNum, int pageSize, Map<String, String> reqPara) {
		// TODO Auto-generated method stub
		List<Role> roleList = roleMapper.selectList(null);
		QueryWrapper<User> queryWrapper = new QueryWrapper<User>();
		queryWrapper.isNull("role_id");
		if(null != reqPara)
		{
			String id = reqPara.get("id");
			if(!StringUtils.isEmpty(id))
			{
				queryWrapper.eq("id", id);
			}
			String name = reqPara.get("name");
			if(!StringUtils.isEmpty(name))
			{
				queryWrapper.like("name", name);
			}
			String phone = reqPara.get("phone");
			if(!StringUtils.isEmpty(phone))
			{
				queryWrapper.like("phone", phone);
			}
			String idCard = reqPara.get("idCard");
			if(!StringUtils.isEmpty(idCard))
			{
				queryWrapper.like("id_card", idCard);
			}
			String passportCard = reqPara.get("passportCard");
			if(!StringUtils.isEmpty(passportCard))
			{
				queryWrapper.like("passport_card", passportCard);
			} 
//			String createDate = reqPara.get("createDate");
//			if(!StringUtils.isEmpty(createDate))
//			{
//				System.out.println(createDate);
//				Date date = new Date(createDate);
//				queryWrapper.eq("create_date", date);
//			}
		}
		Page<User> page = new Page<User>(pageNum,pageSize);
		Page<User> ipage = userMapper.selectPage(page, queryWrapper);
		//查分销表，看分销层级，如果分销层级是0就是业务员，不是0就是普通会员
		List<DistrUser> allDistrUser = distrUserService.getAllDistrUser();
		Map<String,DistrUser> distrUserMap = new HashMap<String, DistrUser>();
		for (DistrUser distrUser : allDistrUser) {
			distrUserMap.put(distrUser.getUserId(), distrUser);
		}
		List<User> records = ipage.getRecords();
		DistrUser distrUser;
		for (User user : records) {
			distrUser = distrUserMap.get(user.getId());
			if(null == distrUser || distrUser.getDislevel() != 0)
			{
				user.setUserRole(0);
			}
			else
			{
				user.setUserRole(1);
			}
			//设置普通会员的消费金额
			Double cost = travelOrderMapper.getCostAmountByUserId(user.getId());
			user.setTotalCost(cost);
		}
		List<User> users = ipage.getRecords();
		
		return users;
	}

	@Override
	public Page<User> getUsersByPage(int pageNum, int pageSize, Map<String, String> reqPara) {
		// TODO Auto-generated method stub
		List<Role> roleList = roleMapper.selectList(null);
		Map<String,String> roleMap = new HashMap<String, String>();
		for (Role role : roleList) {
			roleMap.put(role.getId(), role.getDescription());
		}
		QueryWrapper<User> queryWrapper = new QueryWrapper<User>();
		if(null == reqPara)
		{
			queryWrapper = null;
		}
		else
		{
			String id = reqPara.get("id");
			if(!StringUtils.isEmpty(id))
			{
				queryWrapper.eq("id", id);
			}
			String name = reqPara.get("name");
			if(!StringUtils.isEmpty(name))
			{
				queryWrapper.like("name", name);
			}
			String phone = reqPara.get("phone");
			if(!StringUtils.isEmpty(phone))
			{
				queryWrapper.eq("phone", phone);
			}
			String createDate = reqPara.get("createDate");
			if(!StringUtils.isEmpty(createDate))
			{
				System.out.println(createDate);
				Date date = new Date(createDate);
				queryWrapper.eq("create_date", date);
			}
		}
		Page<User> page = new Page<User>(pageNum,pageSize);
		Page<User> ipage = userMapper.selectPage(page, queryWrapper);
		return ipage;
	}

	@Override
	public UserVo getUserById(String id) {
		// TODO Auto-generated method stub
		UserVo userVo = userMapper.getUserById(id);
		DistrUserVo distrUser = distrUserService.getDistrUserByUserId(id);
		if(null == distrUser || distrUser.getDislevel() != 0)
		{
			userVo.setUserRole(0);
		}
		else
		{
			userVo.setUserRole(1);
		}
		return userVo;
	}

	@Override
	public void updateUser(User user) {
		// TODO Auto-generated method stub
		//前台没有设置账号状态的，这里维护成数据库的状态
		User u = userMapper.selectById(user.getId());
		if(null != u)
		{
			user.setStatus(u.getStatus());
		}
		userMapper.updateById(user);
	}

	@Override
	public List<Role> getAllRoles() {
		// TODO Auto-generated method stub
//		QueryWrapper<Role> wrapper = new QueryWrapper<Role>();
//		wrapper.lt("power", 99);
//		return roleMapper.selectList(wrapper);
		List<Role> returnRoles = new ArrayList<Role>();
		User loginUser = getCurrentUser();
		Role loginUserRole = roleMapper.selectById(loginUser.getRoleId());
		if(null == loginUserRole)
		{
			return returnRoles;
		}
		List<Role> allRoles = roleMapper.selectList(null);
		for (Role role : allRoles) {
			if(loginUserRole.getPower() >= role.getPower())
			{
				returnRoles.add(role);
			}
		}
		return returnRoles;
	}

	@Override
	public List<Permission> getAllPermissions() {
		// TODO Auto-generated method stub
		return permissionMapper.selectList(null);
	}

	@Override
	public void updateUserRole(String userId, String roleId) {
		// TODO Auto-generated method stub
		User user = queryUserById(userId);
		user.setUpdateDate(new Date());
		user.setRoleId(roleId);
		userMapper.updateById(user);
	}

	@Override
	public void deleteUser(String id) {
		// TODO Auto-generated method stub
		userMapper.deleteById(id);
	}

	@Override
	public String modifyPassword(String userId, String newPassword) {
		// TODO Auto-generated method stub
		User user = userMapper.selectById(userId);
		String orginPassword = user.getPassword();
		try {
				user.setPassword(MD5Utils.getMD5Str(newPassword));
				userMapper.updateById(user);
				return "OK";
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return e.getMessage();
		}
	}

	@Override
	public User getCurrentUser() {
		// 目前shiro中存放的是登录用户的手机号
		Object object = SecurityUtils.getSubject().getPrincipal();
		User user = null;
		if (object != null) {
			String phone = object.toString();
			List<User> userList = userMapper.getByPhone(phone);
			if (userList.size() > 0)
				user = userList.get(0);
		}
		return user;
	}

	@Override
	public User queryUserById(String userId) {
		// TODO Auto-generated method stub
		return userMapper.selectById(userId);
	}

	@Override
	public Map<String,List<Object>> getUserCountByDays(Date startDate, Date endDate) {
		// TODO Auto-generated method stub
		Map<String,List<Object>> returnResult = new HashMap<String, List<Object>>();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
		String startTime = sdf.format(startDate);
		String endTime = sdf.format(endDate);
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(startDate);
		calendar.set(Calendar.HOUR_OF_DAY,0);
		calendar.set(Calendar.MINUTE, 0);
		calendar.set(Calendar.SECOND, 0);
		List<Object> dateList = new ArrayList<Object>();
		while(calendar.getTime().getTime()<=endDate.getTime())
		{
			dateList.add(sdf.format(calendar.getTime()));
			calendar.add(Calendar.DAY_OF_YEAR, 1);
		}
		returnResult.put("xAxis", dateList);
		
		Map<String,String> reqMap = new HashMap<String, String>();
		reqMap.put("startDate", startTime);
		reqMap.put("endDate", endTime);
		List<FormReport> userReport = userMapper.getUserCountByDays(reqMap);
		List<Object> countList = new ArrayList<Object>();
		Map<String,Integer> dataMap = new HashMap<String, Integer>();
		for (FormReport formReport : userReport) {
			dataMap.put(formReport.getStrKey(), formReport.getCount());
		}
		for (Object object : dateList) {
			if(dataMap.containsKey(object))
			{
				countList.add(dataMap.get(object));
			}
			else
			{
				countList.add(0);
			}
		}
		returnResult.put("userDate", countList);
		return returnResult;
	}

	@Override
	public IPage<UserVo> getPage(Map<String, Object> queryMap, Integer page, Integer rows) {
		Page<UserVo> pageSize = new Page<UserVo>(page, rows);
		Page<UserVo> pageInfo = userMapper.getPage(pageSize, queryMap);
		return pageInfo;
	}

	@Override
	public List<Permission> getPermissionsByUserId(String userId) {
		// TODO Auto-generated method stub
		List<Permission> selectList = rolePermissionMapper.selectPermissionsByUserId(userId);
		return selectList;
	}

	@Override
	public List<TravelMenu> getMenusInUser(String userId) {
		// TODO Auto-generated method stub
		List<TravelMenu> menuList = roleMenuMapper.selectMenusByUserId(userId);
		Map<String,TravelMenu> menuMap =new HashMap<String, TravelMenu>();
		for (TravelMenu travelMenu : menuList) {
			menuMap.put(travelMenu.getId(), travelMenu);
		}
		List<TravelMenu> childen = new ArrayList<TravelMenu>();
		List<TravelMenu> result = new ArrayList<TravelMenu>();
		TravelMenu father = null;
		for (TravelMenu travelMenu : menuList) {
			String fatherId = travelMenu.getFatherMenuId();
			if(StringUtils.isEmpty(fatherId))
			{
				//如果自己是一级标签
				childen = travelMenu.getChilden();
				if(null == childen)
				{
					childen = new ArrayList<TravelMenu>();
					travelMenu.setChilden(childen);
				}
				result.add(travelMenu);
			}
			else 
			{
				//如果自己是二级标签,拿到父标签并把自己加入到父标签的子集中
				father = menuMap.get(fatherId);
				if(null != father)
				{
					childen = father.getChilden();
					if(null == childen)
					{
						childen = new ArrayList<TravelMenu>();
						father.setChilden(childen);
					}
					childen.add(travelMenu);
				}
			}
		}
		return result;
	}

}
